const { Sequelize, DataTypes } = require('sequelize');
const fs = require('fs');
const sequelize = new Sequelize({ dialect: 'sqlite', storage: 'database.sqlite' });

// 定义会话模型
const Conversation = sequelize.define('Conversation', {
  name: { type: DataTypes.STRING, allowNull: false }
});

// 定义消息模型（关联会话）
const Message = sequelize.define('Message', {
  content: { type: DataTypes.TEXT, allowNull: false },
  type: { type: DataTypes.ENUM('text', 'image'), defaultValue: 'text' },
  sender: { type: DataTypes.ENUM('user', 'bot'), allowNull: false },
  timestamp: { type: DataTypes.DATE, defaultValue: DataTypes.NOW } // 添加时间戳字段
});

// 建立关联
Conversation.hasMany(Message, { foreignKey: 'conversation_id' });
Message.belongsTo(Conversation, { foreignKey: 'conversation_id' });

async function init() {
  await sequelize.sync({ force: true });
  
// 创建测试会话和消息
const conv1 = await Conversation.create({ name: '技术支持会话' });

// 将图片转换为 Base64 字符串
const imageBuffer = fs.readFileSync('example.jpg'); // 假设图片路径为 example.jpg
const base64Image = imageBuffer.toString('base64');

await Message.bulkCreate([
  { conversation_id: conv1.id, content: '我的账号无法登录', sender: 'user' },
  { conversation_id: conv1.id, content: '请检查网络连接', sender: 'bot' },
  { conversation_id: conv1.id, content: base64Image, type: 'image', sender: 'user' }
]);

const conv2 = await Conversation.create({ name: '产品咨询' });
await Message.bulkCreate([
  { conversation_id: conv2.id, content: '这款产品有现货吗？', sender: 'user' },
  { conversation_id: conv2.id, content: '目前库存充足', sender: 'bot' }
]);

  console.log('数据库初始化完成！');
}

init();